package org.marlin.http.http;

import org.apache.commons.lang3.StringUtils;
import org.marlin.http.server.ServerBean;

import java.util.HashMap;
import java.util.Map;


/**
 * init version 1.5.0
 * think support Tree Find 。
 *
 * @author Jack ZG
 * @since 1.0.0
 */
@Deprecated
public class UriTree {
    private Map<String, UriTree> subUris = new HashMap<>();
    private boolean havePathUrl;
    private String name;
    private ServerBean serverBean;

    public void addUri(String url, ServerBean bean) {
        if (StringUtils.startsWith(url, "/")) {
            url = url.substring(1);
        }
        String[] paths = url.split("/");
        String subUrl = StringUtils.substring(url, (url.indexOf("/") == -1) ? 0 : url.indexOf("/"));
        if (paths != null && paths.length > 0 && StringUtils.isNotEmpty(paths[0])) {
            UriTree tree = this.subUris.get(paths[0]);
            if (tree == null) {
                tree = new UriTree();
            }
            if (StringUtils.contains(subUrl, "/")) {
                tree.addUri(subUrl, bean);
            } else {
                tree.setServerBean(bean);
            }
            this.subUris.put(paths[0], tree);
        }
    }

    public boolean isHasMore() {
        return !this.subUris.isEmpty();
    }

    public Parameter getParams() {
        return null;
    }


    public static void main(String[] args) throws UrlNotFindException {
    }


    public UriTree getTree(String servletPath) throws UrlNotFindException {
        if (StringUtils.startsWith(servletPath, "/")) {
            servletPath = servletPath.substring(1);
        }
        String[] paths = servletPath.split("/");
        if (paths != null && paths.length > 0 && StringUtils.isNotEmpty(paths[0])) {
            UriTree uriTree = this.subUris.get(paths[0]);
            if (uriTree.isHasMore()) {
                for (int i = 1, size = paths.length; i < size; ) {
                    uriTree = uriTree.getSubUris().get(paths[i]);
                    if (uriTree != null) {
                        i++;
                        continue;
                    }
                    throw new UrlNotFindException(servletPath);
                }
            }

            return uriTree;
        }
        throw new UrlNotFindException(servletPath);
    }

    public Map<String, UriTree> getSubUris() {
        return this.subUris;
    }

    public ServerBean getServerBean() {
        return this.serverBean;
    }

    public void setServerBean(ServerBean serverBean) {
        this.serverBean = serverBean;
    }

    public void setSubUris(Map<String, UriTree> subUris) {
        this.subUris = subUris;
    }
}

